import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { ElMessage } from 'element-plus'

/* -------------------- 路由配置 -------------------- */
const routes: RouteRecordRaw[] = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/LoginView.vue'),
    meta: { requiresAuth: false, title: '登录', isMenu: false }
  },
  {
    path: '/',
    component: () => import('@/layouts/MainLayout.vue'),
    meta: { requiresAuth: true },
    children: [
      {
        path: '',
        name: 'dashboard',
        component: () => import('@/views/DashboardView.vue'),
        meta: { requiresAuth: true, title: '仪表盘', icon: 'icon-a-ziyuan878', isMenu: true }
      },
      {
        path: 'merchant',
        name: 'merchant',
        meta: { requiresAuth: true, title: '商家管理', icon: 'icon-shouye-zhihui', isMenu: true },
        children: [
          {
            path: 'audit',
            name: 'merchantAudit',
            component: () => import('@/views/merchant/MerchantAudit.vue'),
            meta: { requiresAuth: true, title: '商家审核', icon: 'icon-review', isMenu: true }
          },
          {
            path: 'list',
            name: 'merchantList',
            component: () => import('@/views/merchant/MerchantList.vue'),
            meta: { requiresAuth: true, title: '商家列表', icon: 'icon-list', isMenu: true }
          }
        ]
      },
      {
        path: 'customer',
        name: 'customer',
        meta: { requiresAuth: true, title: '客户管理', icon: 'icon-tianxuangouren', isMenu: true },
        children: [
          {
            path: 'list',
            name: 'customerView',
            component: () => import('@/views/customer/CustomerView.vue'),
            meta: { requiresAuth: true, title: '客户管理', icon: 'icon-list', isMenu: true }
          }
        ]
      },
      {
        path: 'product',
        name: 'product',
        meta: { requiresAuth: true, title: '商品管理', icon: 'icon-a-ziyuan822', isMenu: true },
        children: [
          {
            path: 'center',
            name: 'productCenter',
            component: () => import('@/views/product/ProductManage.vue'),
            meta: { requiresAuth: true, title: '商品中心', icon: 'icon-center', isMenu: true }
          }
        ]
      },
      {
        path: 'order',
        name: 'order',
        meta: { requiresAuth: true, title: '订单管理', icon: 'icon-a-ziyuan846', isMenu: true },
        children: [
          {
            path: 'list',
            name: 'orderList',
            component: () => import('@/views/order/OrderList.vue'),
            meta: { requiresAuth: true, title: '订单列表', icon: 'icon-list', isMenu: true }
          }
        ]
      },
      {
        path: 'notice',
        name: 'notice',
        meta: { requiresAuth: true, title: '通知管理', icon: 'icon-duanxin', isMenu: true },
        children: [
          {
            path: 'cash',
            name: 'cashManage',
            component: () => import('@/views/notice/CashManage.vue'),
            meta: { requiresAuth: true, title: '提现管理', icon: 'icon-cash', isMenu: true }
          },
          {
            path: 'distribution',
            name: 'distributionManage',
            component: () => import('@/views/notice/DistributionManage.vue'),
            meta: { requiresAuth: true, title: '分销管理', icon: 'icon-distribution', isMenu: true }
          },
          {
            path: 'ad',
            name: 'adManage',
            component: () => import('@/views/notice/AdManage.vue'),
            meta: { requiresAuth: true, title: '广告管理', icon: 'icon-ad', isMenu: true }
          },
          {
            path: 'rule',
            name: 'ruleManage',
            component: () => import('@/views/notice/RuleManage.vue'),
            meta: { requiresAuth: true, title: '须知管理', icon: 'icon-rule', isMenu: true }
          },
          {
            path: 'text',
            name: 'textEditor',
            component: () => import('@/views/notice/TextEditor.vue'),
            meta: { requiresAuth: true, title: '文本编辑', icon: 'icon-list', isMenu: true }
          },
          {
            path: 'activity',
            name: 'activityManage',
            component: () => import('@/views/notice/ActivityManage.vue'),
            meta: { requiresAuth: true, title: '活动管理', icon: 'icon-activity', isMenu: true }
          },
          {
            path: 'prize',
            name: 'prizeManage',
            component: () => import('@/views/notice/PrizeManage.vue'),
            meta: { requiresAuth: true, title: '奖品管理', icon: 'icon-prize', isMenu: true }
          }
        ]
      }
    ]
  }
]

/* -------------------- 路由实例 -------------------- */
const router = createRouter({
  history: createWebHistory(),
  routes
})

/* -------------------- 路由守卫 -------------------- */
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const isLoginPage = to.path === '/login'

  // 调试开关
  const DEBUG = true
  const log = (...args: any[]) => DEBUG && console.log('[Router Guard]', ...args)

  log('目标路由:', to.path, 'token 存在:', !!token)

  // 1. 没 token 且不在登录页 → 去登录
  if (!token && !isLoginPage) {
    log('❌ 无 token → 去登录页')
    Promise.resolve().then(() => ElMessage.warning('请先登录'))
    return next({ path: '/login', replace: true })
  }

  // 2. 有 token 还访问登录页 → 回首页
  if (token && isLoginPage) {
    log('✅ 已登录 → 回首页')
    return next({ path: '/', replace: true })
  }

  // 3. 其余放行
  log('✅ 放行')
  next()
})

export default router
